import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Query } from 'react-apollo'
import PropTypes from 'prop-types'
import { Grid } from 'semantic-ui-react'
import { validForm as validFormDucks } from 'ducks'
import Loading from 'components/loading'
import ErrorPage from 'components/errorPage'

class TableForm extends Component {
  static propTypes = {
    children: PropTypes.node.isRequired,
  }

  componentWillUnmount = () => {
    const { actionResetForm } = this.props
    actionResetForm()
  }

  render() {
    const {
      children, initQuery, actionReciveQueryData, isFormDataInit,
    } = this.props
    if (initQuery) {
      return (
        <Query
          query={initQuery.query}
          variables={initQuery.variables}
          fetchPolicy="network-only"
          onCompleted={(data) => {
            if (data && data[initQuery.tableName] && data[initQuery.tableName].length > 0) {
              actionReciveQueryData(data[initQuery.tableName][0])
            }
          }}
        >
          {({ loading, error, data }) => {
            if (loading) return <Loading />
            if (error) return <ErrorPage msg={error.message} />
            if (isFormDataInit) {
              return (
                <Grid>
                  <Grid.Row>
                    <Grid.Column>{children}</Grid.Column>
                  </Grid.Row>
                </Grid>
              )
            }
            return <div />
          }}
        </Query>
      )
    }
    return (
      <Grid>
        <Grid.Row>
          <Grid.Column>{children}</Grid.Column>
        </Grid.Row>
      </Grid>
    )
  }
}

const mapStateToProps = state => ({
  isFormDataInit: validFormDucks.selectors.isFormDataInit(state),
})

const mapDispatchToProps = {
  actionResetForm: validFormDucks.creators.actionResetForm,
  actionReciveQueryData: validFormDucks.creators.actionReciveQueryData,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(TableForm)
